// import WebSocketServer from "./server.d"
import { onBeforeUnmount, onMounted, ref } from 'vue';
import WebSocketClient from './client.d';
// import WebSocket from 'ws';

export enum SocketType {
    SERVER_ONLY = "SERVER_ONLY",
    CLIENT_ONLY = "CLIENT_ONLY",
    PEER_POINT = "PEER_POINT",
}

type MsgHandler = (data: string) => void

type PusherConfig = {
    type: SocketType,
    wsRemote: string,
    msgHandler: MsgHandler,
    pushAPI?: string
}

// const send = (data: string) => {
//     console.log("send", data);
// }

// const onReceive = (handler: MsgHandler) => {
//     console.log("onReceive", handler);
// }

const usePusher = ({ wsRemote, pushAPI, msgHandler }: PusherConfig) => {

    const ws = ref<WebSocket>()
    const sendMsg = ref<(msg: string) => void>()
    const closeConn = ref<() => void>()

    const pushMsg = (ids: string[], msg: string) => {
        // 发送POST请求
        fetch(pushAPI!, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ids,
                msg
            })
        })
            .then(response => response.json())
            .then(data => {
                console.log('推送发送成功', data);
            })
            .catch(error => {
                console.error('推送发送失败', error);
            });
    }

    onMounted(() => {
        /* 创建客户端 */
        ws.value = new WebSocket(wsRemote);

        sendMsg.value = (msg: string) => ws.value!.send(msg);
        closeConn.value = () => ws.value!.close()

        ws.value.onopen = () => {
            console.log('WebSocketClient 连接已打开');
            // ws.send('Hello, WebSocket!');
        };

        ws.value.onmessage = (e) => {
            console.log('WebSocketClient 收到消息:', e.data.toString());
            msgHandler(e.data.toString())
        }

        ws.value.onclose = () => {
            console.log('WebSocketClient 连接已关闭');
        };
    })

    onBeforeUnmount(() => {
        ws.value!.close()
    })

    return {
        sendMsg,
        pushMsg,
        closeConn
    }

}

export default usePusher